﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WFClient
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 用来存放连接服务的IP地址和端口号，对应的Socket (这个为了以后的扩展用，现在暂时没用)
        /// </summary>
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();

        /// <summary>
        /// 负责通信的Socket
        /// </summary>
        Socket socketSend;    

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //不检测跨线程之间的空间调用
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 建立连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void connectionSer_Click(object sender, EventArgs e)
        {
            try
            {
                //创建负责通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //获取服务端的IP
                IPAddress ip = IPAddress.Parse(sipAddress.Text.Trim());

                //获取服务端的端口号
                IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(serverPort.Text.Trim()));

                //获得要连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(port);
                
                //新建线程，去接收客户端发来的信息
                Thread td = new Thread(AcceptMgs);
                td.IsBackground = true;
                td.Start();
            }
            catch { }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //PrintData tempData = new PrintData();
                //tempData.TemplatePath = @"C:\templates";
                //tempData.TemplateName = "lablete.lbx";

                //Dictionary<string, string> printData = new Dictionary<string, string>();
                //printData.Add("objName", sendMessage.Text);
                //printData.Add("objNum", "test001");
                //tempData.PrintDataList = printData;

                ////实体序列化和反序列化  
                //string json1 = SerializeObject(tempData);

                //byte[] buffer = Encoding.UTF8.GetBytes(json1);
                byte[] buffer = Scoket_ZuJieTest();
                //将字节数组传递给客户端
                socketSend.Send(System.Text.Encoding.Default.GetBytes(buffer.ValueToX2String()));
                sendMessage.Text = "";
              
            }
            catch { }   
        }
        //private void Socket_notice(string Ip, int port, int orderid, byte[] bytes)
        //{
        //    //int port = 8885;
        //    //string host = "127.0.0.1";139.129.55.112//服务器端ip地址123.207.149.46
        //    IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("123.207.149.46"), 8885);
        //    Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    clientSocket.Connect(ipe);

        //    //请求消息体
        //    byte[] bBody = StringToByte(Ip + ":" + port + "," + orderid, Encoding.UTF8);
        //    //long shebeiid = 1;
        //    //byte[] bBody = BitConverter.GetBytes(shebeiid);
        //    //消息头
        //    MessageHead head = new MessageHead(bBody.Length, 3);
        //    byte[] bHead = head.ToStream();
        //    //消息尾
        //    byte[] bEnd = bytes;
        //    //合体
        //    byte[] sendBytes = ZuHe(bHead, bBody, bEnd);

        //    clientSocket.Send(System.Text.Encoding.Default.GetBytes(sendBytes.ValueToX2String()));
        //}

        private byte[] Scoket_ZuJieTest()
        {

            long aa = 1;
            byte[] bBody = BitConverter.GetBytes(aa);
            MessageHead head = new MessageHead(bBody.Length, 1);
            byte[] bHead = head.ToStream();
            byte[] bEnd = new byte[] { 0x01 };
            byte[] sendBytes = ZuHe(bHead, bBody, bEnd);
            //Socket_FaShi(sendBytes);
            return sendBytes;
        }
        private byte[] Scoket_GuiHuanUrlTest()
        {

            long aa = 1;
            byte[] bBody = BitConverter.GetBytes(aa);
            MessageHead head = new MessageHead(bBody.Length, 1);
            byte[] bHead = head.ToStream();
            byte[] bEnd = new byte[] { 0x02 };
            byte[] sendBytes = ZuHe(bHead, bBody, bEnd);
            //Socket_FaShi(sendBytes);
            return sendBytes;
        }
        private byte[] Scoket_GuiHuanChenGongTest(long orderid,int cth)
        {
            byte[] aa = BitConverter.GetBytes(orderid);
            byte[] bBody = new byte[9];
            Buffer.BlockCopy(aa, 0, bBody, 0, 8);
            bBody[8] = Convert.ToByte(cth);
            MessageHead head = new MessageHead(bBody.Length, 4);
            byte[] bHead = head.ToStream();
            byte[] bEnd = new byte[] { 0x02 };
            byte[] sendBytes = ZuHe(bHead, bBody, bEnd);
            return sendBytes;
        }
        private byte[] Scoket_ChuHuoTest(long orderid)
        {
            byte[] aa = BitConverter.GetBytes(orderid);
            byte[] bBody = new byte[9];
            Buffer.BlockCopy(aa, 0, bBody, 0, 8);
            bBody[8] = 1;
            MessageHead head = new MessageHead(bBody.Length, 4);
            byte[] bHead = head.ToStream();
            byte[] bEnd = new byte[] { 0x01 };
            byte[] sendBytes = ZuHe(bHead, bBody, bEnd);
            //Socket_FaShi(sendBytes);
            return sendBytes;
        }
        //private void Socket_FaShi(byte[] sendBytes)
        //{
        //    byte[] result = new byte[1024];
        //    IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("123.207.149.46"), 8885);
        //    Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //    clientSocket.Connect(ipe);
        //    int receiveLength = clientSocket.Receive(result);
        //    clientSocket.Send(System.Text.Encoding.Default.GetBytes(sendBytes.ValueToX2String()));
        //}
        private byte[] ZuHe(byte[] bHead, byte[] bBody, byte[] bEnd)
        {
            byte[] sendBytes = new byte[bHead.Length + bBody.Length + bEnd.Length];
            Buffer.BlockCopy(bHead, 0, sendBytes, 0, bHead.Length);
            Buffer.BlockCopy(bBody, 0, sendBytes, bHead.Length, bBody.Length);
            Buffer.BlockCopy(bEnd, 0, sendBytes, bHead.Length + bBody.Length, bEnd.Length);
            return sendBytes;
        }
        private Byte[] StringToByte(String s, Encoding encoding)
        {
            return encoding.GetBytes(s);
        }
        /// <summary>
        /// 客户端接收服务器端返回的数据
        /// </summary>
        private void AcceptMgs()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }

                    //信息显示
                    string strMsg = Encoding.UTF8.GetString(buffer, 0, r);
                    //0800000001000000E30200000000000001
                    var msgtype = int.Parse(strMsg.Substring(8, 2));
                    var msgtend = int.Parse(strMsg.Substring(strMsg.Length-2, 2));
                    var msghead = strMsg.Substring(0, 8);
                    byte[] headarray=new byte[4];
                    for (int i = 0; i < headarray.Length; i++)
                    {
                        headarray[i] = Convert.ToByte(msghead.Substring(i * 2, 2), 16);
                    }
                    var head = BitConverter.ToInt32(headarray, 0);
                    if (msgtype == 3 && msgtend==1)
                    {
                        var str = strMsg.Substring(16, 16);
                        byte[] aa = new byte[str.Length / 2];
                        for (int i = 0; i < aa.Length; i++)
                        {
                            aa[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                        }
                        long orderid = BitConverter.ToInt64(aa, 0);
                        
                        byte[] result = Scoket_ChuHuoTest(orderid); ;
                        //将字节数组传递给客户端
                        socketSend.Send(System.Text.Encoding.Default.GetBytes(result.ValueToX2String()));
                    }
                    if (msgtype == 3 && msgtend == 2)
                    {
                        var str = strMsg.Substring(16, 16);
                        byte[] aa = new byte[str.Length / 2];
                        for (int i = 0; i < aa.Length; i++)
                        {
                            aa[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                        }
                        long orderid = BitConverter.ToInt64(aa, 0);
                        int cth = 1;
                        byte[] result = Scoket_GuiHuanChenGongTest(orderid,cth); ;
                        //将字节数组传递给客户端
                        socketSend.Send(System.Text.Encoding.Default.GetBytes(result.ValueToX2String()));
                    }
                    if (msgtype == 1 && msgtend == 2)
                    {
                        var str = strMsg.Substring(16, head*2);
                        byte[] urlarray=new byte[str.Length/2];
                        for (int i = 0; i < urlarray.Length; i++)
                        {
                            urlarray[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
                        }
                        string url = System.Text.Encoding.Default.GetString(urlarray);
                        Form2 form2 = new Form2(url);
                        form2.ShowDialog();
                    }
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ": " + strMsg);
                }
            }
            catch(Exception ex)
            {
                var aa=ex.Message;
            }
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMsg(string message)
        {
            resultMsg.AppendText(message + "\r\n");
        }

        /// <summary>  
        /// 将对象序列化为JSON格式  
        /// </summary>  
        /// <param name="o">对象</param>  
        /// <returns>json字符串</returns>  
        public string SerializeObject(object o)
        {
            string json = JsonConvert.SerializeObject(o);
            return json;
        }

        private void button1_Click(object sender, EventArgs e)
        {
          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = Scoket_GuiHuanUrlTest();
                //将字节数组传递给客户端
                socketSend.Send(System.Text.Encoding.Default.GetBytes(buffer.ValueToX2String()));
                //sendMessage.Text = "";
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                throw;
            }
        }
    }
}
